
package at.fhj.ase.crypto.client;

import org.apache.log4j.Logger;

import at.fhj.ase.crypto.client.net.ServerConnector;
import at.fhj.ase.crypto.common.util.StringUtil;

/**
 * Class only responsible for
 * <ul>
 * <li>parsing the application arguments and<br>
 * <li>starting the application via {@link Client#main(String[])}-method.
 * </ul>
 * The arguments to that method should be a valid hostname and port number, which means > 1023 ("well known ports").<br>
 * If the arguments are not correct, a small usage is printed and the program exits with error-code <code>1</code>.
 * 
 * @author sfe | www.fh-joanneum.at | Practical Aspects of Cryptography
 */
public class Client {
  /** The sole logger instance */
  private static final Logger logger = Logger.getLogger(Client.class);

  /**
   * Starting point of the server application.
   * 
   * @param args the application arguments which should be the a hostname and a port number (> 1023)
   */
  public static void main(String args[]) {
    if (args.length != 2) {
      logger.error("Invalid arguments, usage:\n" + printUsage());
      System.exit(1);
    }

    final String HOST = StringUtil.checkLengthDefaults(args[0]);
    final int PORT = Integer.parseInt(StringUtil.checkLength(args[1], 1, 5));
    new Client(HOST, PORT); // start the client; each exception ends up in stopping the application
  }

  /** @return a small application usage information if it has been called with wrong arguments */
  private static String printUsage() {
    return "secureChatFedlClient <HOST> <PORT>";
  }

  /**
   * Constructor (private, called by main-method) responsible for really starting the application and catching all {@link Throwable}s.<br>
   * If a {@link Throwable} is caught, the application will exit with error-code <code>1</code>.
   * 
   * @param host the host name we want to connect to (e.g. <code>localhost</code> or an IP address)
   * @param port the port number this server should be started with (> 1023)
   */
  private Client(final String host, final int port) {
    try {
      ServerConnector.INSTANCE.init(host, port);
    } catch (Throwable t) {
      logger.error("Could not start client, exiting with error-code 1...", t);
      System.exit(1);
    }
  }
}
